package com.jinlejia.erp.ui.house;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.SearchHistoryAdapter;
import com.jinlejia.erp.adapter.SearchHouseAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.BaseActivity;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.EstateBean;
import com.jinlejia.erp.bean.RentHistoryBean;
import com.jinlejia.erp.bean.SelectHistoryBean;
import com.jinlejia.erp.bean.ShsHistoryBean;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivitySearchHouseBinding;
import com.jinlejia.erp.ui.common.CommonDeleteDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class SearchHouseActivity extends BaseActivity {

    SearchHistoryAdapter historyAdapter;
    SearchHouseAdapter adapter;

    private ActivitySearchHouseBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_search_house);
        binding.btBack.setOnClickListener(this::onClick);
        binding.btClear.setOnClickListener(this::onClick);

        initView();
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                Intent data = new Intent();
                data.putExtra("name", "");
                setResult(RESULT_OK, data);
                finish();
                break;
            case R.id.bt_clear:
                binding.etSearchText.setText("");
                break;
            default:
                break;
        }
    }

    private void initView() {
        binding.yfrvSearchResult.setHasFixedSize(true);
        binding.yfrvSearchResult.setLayoutManager(new LinearLayoutManager(this));
        binding.yfrvSearchResult.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));

        //搜索历史
        ArrayList historyList = new ArrayList();
        if (getIntent().getStringExtra("type").equals("rent")) {
            historyList.addAll(DbUtil.getDB(SearchHouseActivity.this).single().query(RentHistoryBean.class));
        } else if (getIntent().getStringExtra("type").equals("shs")) {
            historyList.addAll(DbUtil.getDB(SearchHouseActivity.this).single().query(ShsHistoryBean.class));
        } else if (getIntent().getStringExtra("type").equals("select")) {
            historyList.addAll(DbUtil.getDB(SearchHouseActivity.this).single().query(SelectHistoryBean.class));
            binding.etSearchText.setHint("请输入楼盘名称");
        }
        Collections.reverse(historyList);
        historyAdapter = new SearchHistoryAdapter(historyList);
        if (historyList.size() > 0)
            historyAdapter.addFooter("清空历史");
        binding.yfrvSearchResult.setAdapter(historyAdapter);
        historyAdapter.setOnFooterViewClickListener((view, o) -> {

            CommonDeleteDialog dialog = new CommonDeleteDialog(SearchHouseActivity.this, "清空历史", "确定清空历史记录?");
            dialog.show();
            dialog.setConfirmListener(() -> {
                if (getIntent().getStringExtra("type").equals("rent")) {
                    DbUtil.getDB(SearchHouseActivity.this).single().deleteAll(RentHistoryBean.class);
                } else if (getIntent().getStringExtra("type").equals("shs")) {
                    DbUtil.getDB(SearchHouseActivity.this).single().deleteAll(ShsHistoryBean.class);
                } else if (getIntent().getStringExtra("type").equals("select")) {
                    DbUtil.getDB(SearchHouseActivity.this).single().deleteAll(SelectHistoryBean.class);
                }
                historyAdapter.getData().clear();
                historyAdapter.changeMode(YfListMode.MODE_EMPTY);
            });

        });
        historyAdapter.setOnItemClickListener((view, o) -> {
            if (getIntent().getStringExtra("type").equals("rent")) {
                RentHistoryBean rhb = new RentHistoryBean(((RentHistoryBean) o).getName());
                DbUtil.getDB(SearchHouseActivity.this).single().delete(WhereBuilder.create(RentHistoryBean.class, "name=?", new String[]{rhb.getName()}));
                DbUtil.getDB(SearchHouseActivity.this).single().save(rhb);
                EventBus.getDefault().post(rhb.getName(), "TAG_SEARCH_RENT");
            } else if (getIntent().getStringExtra("type").equals("shs")) {
                ShsHistoryBean shb = new ShsHistoryBean(((ShsHistoryBean) o).getName());
                DbUtil.getDB(SearchHouseActivity.this).single().delete(WhereBuilder.create(ShsHistoryBean.class, "name=?", new String[]{shb.getName()}));
                DbUtil.getDB(SearchHouseActivity.this).single().save(shb);
                EventBus.getDefault().post(shb.getName(), "TAG_SEARCH_SHS");
            } else if (getIntent().getStringExtra("type").equals("select")) {
                SelectHistoryBean rshb = new SelectHistoryBean((((SelectHistoryBean) o)).getName());
                DbUtil.getDB(SearchHouseActivity.this).single().delete(WhereBuilder.create(SelectHistoryBean.class, "name=?", new String[]{rshb.getName()}));
                DbUtil.getDB(SearchHouseActivity.this).single().save(rshb);
                Intent data = new Intent();
                data.putExtra("name", rshb.getName());
                setResult(RESULT_OK, data);
            }
            finish();
        });

        //搜索结果
        ArrayList list = new ArrayList();
        adapter = new SearchHouseAdapter(list, binding.etSearchText.getText().toString());
        adapter.setOnItemClickListener((view, o) -> {
            if (getIntent().hasExtra("type") && o instanceof EstateBean && getIntent().getStringExtra("type").equals("select")) {
                Intent data = new Intent();
                data.putExtra("name", ((EstateBean) o).getEstateName());
                setResult(RESULT_OK, data);
                SelectHistoryBean rshb = new SelectHistoryBean(((EstateBean) o).getEstateName());
                ArrayList<SelectHistoryBean> shbList = DbUtil.getDB(SearchHouseActivity.this).single().query(SelectHistoryBean.class);
                if (shbList.size() == 20) {
                    //数量达到20，删除第一个
                    DbUtil.getDB(SearchHouseActivity.this).single().delete(shbList.get(0));
                }
                if (DbUtil.getDB(SearchHouseActivity.this).single().query(new QueryBuilder<>(SelectHistoryBean.class)
                        .whereEquals("name", rshb.getName())).size() == 0) {
                    //不包含，直接存
                    DbUtil.getDB(SearchHouseActivity.this).single().save(rshb);
                } else {
                    //已经存在，先删除再存
                    DbUtil.getDB(SearchHouseActivity.this).single().delete(WhereBuilder.create(SelectHistoryBean.class, "name=?", new String[]{rshb.getName()}));
                    DbUtil.getDB(SearchHouseActivity.this).single().save(rshb);
                }

            } else if (getIntent().hasExtra("type") && o instanceof EstateBean && getIntent().getStringExtra("type").equals("rent")) {
                EventBus.getDefault().post(((EstateBean) o).getEstateName(), "TAG_SEARCH_RENT");
                RentHistoryBean rhb = new RentHistoryBean(((EstateBean) o).getEstateName());
                ArrayList<RentHistoryBean> shbList = DbUtil.getDB(SearchHouseActivity.this).single().query(RentHistoryBean.class);
                if (shbList.size() == 20) {
                    //数量达到20，删除第一个
                    DbUtil.getDB(SearchHouseActivity.this).single().delete(shbList.get(0));
                }
                if (DbUtil.getDB(SearchHouseActivity.this).single().query(new QueryBuilder<>(RentHistoryBean.class)
                        .whereEquals("name", rhb.getName())).size() > 0)
                    //已经存在，先删除再存
                    DbUtil.getDB(SearchHouseActivity.this).single().delete(WhereBuilder.create(RentHistoryBean.class, "name=?", new String[]{rhb.getName()}));
                DbUtil.getDB(SearchHouseActivity.this).single().save(rhb);
            } else if (getIntent().hasExtra("type") && o instanceof EstateBean && getIntent().getStringExtra("type").equals("shs")) {
                EventBus.getDefault().post(((EstateBean) o).getEstateName(), "TAG_SEARCH_SHS");
                ShsHistoryBean shb = new ShsHistoryBean(((EstateBean) o).getEstateName());
                ArrayList<ShsHistoryBean> shbList = DbUtil.getDB(SearchHouseActivity.this).single().query(ShsHistoryBean.class);
                if (shbList.size() == 20) {
                    //数量达到20，删除第一个
                    DbUtil.getDB(SearchHouseActivity.this).single().delete(shbList.get(0));
                }
                if (DbUtil.getDB(SearchHouseActivity.this).single().query(new QueryBuilder<>(ShsHistoryBean.class)
                        .whereEquals("name", shb.getName())).size() > 0)
                    //已经存在，先删除再存
                    DbUtil.getDB(SearchHouseActivity.this).single().delete(WhereBuilder.create(ShsHistoryBean.class, "name=?", new String[]{shb.getName()}));
                DbUtil.getDB(SearchHouseActivity.this).single().save(shb);

            }
            finish();
        });

        binding.etSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    binding.yfrvSearchResult.setAdapter(adapter);
                    searchData();
                    binding.btClear.setVisibility(View.VISIBLE);
                } else {
                    binding.yfrvSearchResult.setAdapter(historyAdapter);
                    binding.btClear.setVisibility(View.INVISIBLE);
                }
            }
        });
        binding.etSearchText.setOnEditorActionListener((arg0, arg1, arg2) -> {
            if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
                if (getIntent().getStringExtra("type").equals("shs")) {
                    EventBus.getDefault().post(arg0.getText().toString(), "TAG_SEARCH_SHS");
                } else {
                    EventBus.getDefault().post(arg0.getText().toString(), "TAG_SEARCH_RENT");
                }
                finish();
            }
            return false;
        });

    }

    private void searchData() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("reNameLike", binding.etSearchText.getText().toString());
        OkHttpUtils.postString()
                .url(ApiConfig.HOUSE_SOURCE_QUERYE_STATE_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(SearchHouseActivity.this, response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            JSONArray list = data.getJSONArray("realEstateList");

                            //数据列表
                            ArrayList<EstateBean> beans = (ArrayList<EstateBean>) JSON.parseArray(list.toString(), EstateBean.class);
                            adapter.setData(beans);
                            adapter.setWord(binding.etSearchText.getText().toString());
                            binding.yfrvSearchResult.setAdapter(adapter);
                        }
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
